import { SensorDataModel } from '../model/SensorDataModel';
import { observer } from '@kit.TelephonyKit';


import { SensorData }  from './SensorData'

class DataParseUtil {
  passJsonData(data: ArrayBuffer): SensorDataModel {
    let result = new SensorDataModel();
    let str = this.arrayBuffer2String(data);
    let jsonValue = JSON.parse(str);
    if (jsonValue.services && jsonValue.services[0]) {
      result.temperature = jsonValue.services[0].properties.temperature;
      // result.pressure = jsonValue.services[0].properties.pressure;
      result.humidity = jsonValue.services[0].properties.humidity;
      result.smoke = jsonValue.services[0].properties.smoke;
      result.illumination = jsonValue.services[0].properties.illumination;
      // result.pm25 = jsonValue.services[0].properties.pm25;
      // result.latitude = jsonValue.services[0].properties.latitude;
      // result.longitude = jsonValue.services[0].properties.longitude;
      console.info('temperature' + result.temperature)
    }
    return result;
  }

  arrayBuffer2String(message: ArrayBuffer): string {
    if (message instanceof ArrayBuffer) {
      let dataView = new DataView(message)
      let str = ""
      for (let i = 0;i < dataView.byteLength; ++i) {
        let c = String.fromCharCode(dataView.getUint8(i))
        str += c
      }
      return str;
    }
  }

  stringToHex(str: string): string {
    let hex = '';
    for (let i = 0; i < str.length; i++) {
      hex += this.unicodeToHex(str[i]);
    }
    return hex;
  }

  unicodeToHex(char: string): string {
    const code = char.charCodeAt(0);
    return code.toString(16).padStart(4, '0');
  }

  arrayBuffer2HexString(arrayBuffer) {
    let hex = ''
    let uint8Array = new Uint8Array(arrayBuffer)
    for (let i = 0; i < uint8Array.length; i++) {
      // 将字节转换为16进制字符串，并添加到hex中
      hex += uint8Array[i].toString(16).padStart(2, '0') // 使用padStart确保总是两位数
    }
    return hex

  }

  hexStringToArrayBuffer(hexString): ArrayBuffer {
    if (!hexString.length) {
      return new ArrayBuffer(0);
    }

    var byteArray = new Uint8Array(hexString.match(/.{2}/g).map(function (byte) {
      return parseInt(byte, 16);
    }));

    return byteArray.buffer;
  }


  sendHexStrToCar(effect: number, action: number, speed?: number): string {
    let data: number[] = [];
    //上位机发送数据的包头为0xFF 0xFC
    data[0] = 0xFF;
    data[1] = 0xFC;
    //数据包长度，排除前面包头都属于数据包长度范围，包括本身
    data[2] = 0x07;
    //功能字，0x11代表上位机发送指令控制小车运动,0x61代表控制车灯
    data[3] = effect;
    //小车类型，该字段未后期丰富小车类型预留，暂无实际作用，暂时传入0x00即可
    data[4] = 0x00;
    //小车运动行为控制，=0停车，=1前进，=2后退，=3左平移，=4右平移，=5左旋转，=6右旋转，=7刹车停止，=8左上移动，=9右上移动，=10右下移动，=11左下移动
    //当effect为控制车灯时，action=0代表关，1代表开，2代表双闪
    data[5] = action;
    //小车速度，0-100，速度越大，速度越快，不传该参数时默认设置为0X00
    if(!speed){
      speed = 0x00;
    }
    data[6] = speed;
    //保留字，暂时传入0X00即可
    data[7] = 0x00;
    //checknum，校验码，从长度的值（下标为2）累加到校验位前的值，再对256取余。
    data[8] = (data[2] + data[3] + data[4] + data[5] + data[6] + data[7]) % 256;
    let result: string = '';
    for (let value of data) {
      result += value.toString(16).length == 1 ? '0' + value.toString(16).toUpperCase() : value.toString(16).toUpperCase();
    }
    return result;
  }

  sendHexToCar(action: number, speed: number): ArrayBuffer {
    let effect: number = 0x11;
    return this.hexStringToArrayBuffer(this.sendHexStrToCar(effect,action, speed));
  }

  ctlLedToCar(action: number): ArrayBuffer {
    let effect: number = 0x61;
    return this.hexStringToArrayBuffer(this.sendHexStrToCar(effect,action));
  }

  parseSensorData(data: string): SensorData {
    // 移除起始和结束标记
    const content = data.slice(1, -1);
    // 解析固定长度字段
    const vehicleType = content.slice(0, 2);
    const functionCode = content.slice(2, 4);
    const lengthStr = content.slice(4, 6);
    // 将长度从16进制字符串转换为数字
    const dataLength = parseInt(lengthStr, 16);
    // 计算数据部分和校验位的位置
    const dataStart = 6;
    const dataEnd = dataStart + dataLength * 2; // 每个字节2个十六进制字符
    const checksumStart = dataEnd;
    const checksumEnd = checksumStart + 2;
    // 提取数据部分和校验位
    const dataSection = content.slice(dataStart, dataEnd);
    const checksum = content.slice(checksumStart, checksumEnd);
    // 解析传感器数据（每4个字符为一组，低位在前）
    const parseValue = (startIndex: number): number => {
      const hexStr = dataSection.slice(startIndex * 4, (startIndex + 1) * 4);
      // 低位在前处理：交换字节顺序
      const lowByte = hexStr.slice(0, 2);
      const highByte = hexStr.slice(2, 4);
      const fullHex = highByte + lowByte;
      return parseInt(fullHex, 16);
    };
    // 解析各个传感器值
    const temperature = parseValue(0);  // 8f0d -> 0d8f = 3471
    const humidity = parseValue(1);     // d80e -> 0ed8 = 3800
    const pressure = parseValue(2);     // 7223 -> 2372 = 9074
    const light = parseValue(3);        // 0000 -> 0000 = 0
    const gas = parseValue(4);          // 0200 -> 0002 = 2
    const pm25 = parseValue(5);         // 1500 -> 0015 = 21
    const latitude = parseValue(6);     // 540e -> 0e54 = 3668
    const longitude = parseValue(7);    // 852e -> 2e85 = 11909

    // 计算校验和（可选：验证校验和）
    const calculateChecksum = (): string => {
      let sum = 0;
      const checkData = content.slice(0, checksumStart);

      for (let i = 0; i < checkData.length; i += 2) {
        const byte = checkData.slice(i, i + 2);
        sum += parseInt(byte, 16);
      }

      return (sum & 0xFF).toString(16).padStart(2, '0');
    };

    const calculatedChecksum = calculateChecksum();
    if (calculatedChecksum !== checksum.toLowerCase()) {
      console.warn(`Checksum mismatch: expected ${calculatedChecksum}, got ${checksum}`);
    }

    return {
      vehicleType,
      functionCode,
      length: dataLength,
      temperature,
      humidity,
      pressure,
      light,
      gas,
      pm25,
      latitude,
      longitude,
      checksum,
      rawData: data
    };
  }
}

export default new DataParseUtil();

